#include "uart.h"
#include "interrupt.h"
#include "timer.h"
#include "memory.h"
#include "task.h"

// 示例任务1：周期性打印计数
void counter_task(void) {
    int counter = 0;
    while(1) {
        uart_puts("Counter task: ");
        // 打印计数
        char num[10];
        int i = 0;
        int temp = counter;
        do {
            num[i++] = temp % 10 + '0';
            temp /= 10;
        } while(temp > 0);
        while(i > 0) {
            uart_putc(num[--i]);
        }
        uart_puts("\n");
        
        counter++;
        for(volatile int i = 0; i < 1000000; i++); // 简单延时
        task_yield();
    }
}

// 示例任务2：内存测试任务
void memory_test_task(void) {
    while(1) {
        uart_puts("Memory test task running...\n");
        
        // 分配和释放内存进行测试
        void* ptr = memory_alloc(100);
        if(ptr) {
            uart_puts("Allocated 100 bytes\n");
            memory_free(ptr);
            uart_puts("Freed memory\n");
        }
        
        for(volatile int i = 0; i < 1000000; i++); // 简单延时
        task_yield();
    }
}

void kernel_main(void) {
    // 初始化串口
    uart_init();
    
    // 打印欢迎信息
    uart_puts("\n\n=== RISC-V OS with Timer, Memory Management and Task Scheduler ===\n\n");
    
    // 初始化中断
    uart_puts("Initializing interrupt system...\n");
    interrupt_init();
    
    // 初始化定时器
    uart_puts("Initializing timer...\n");
    timer_init();
    
    // 初始化内存管理
    uart_puts("Initializing memory management...\n");
    memory_init();
    
    // 初始化任务系统
    uart_puts("Initializing task scheduler...\n");
    task_init();
    
    // 启用全局中断
    uart_puts("Enabling global interrupts...\n");
    interrupt_enable();
    
    uart_puts("\nSystem is ready! You can interact with the system.\n");
    uart_puts("Commands:\n");
    uart_puts("  't' - Show system uptime\n");
    uart_puts("  'i' - Show timer info\n");
    uart_puts("  'm' - Show memory stats\n");
    uart_puts("  'a' - Run memory test\n");
    uart_puts("  'l' - List all tasks\n");
    uart_puts("  'c' - Create counter task\n");
    uart_puts("  'e' - Create memory test task\n");
    uart_puts("  'y' - Force task switch (yield)\n");
    uart_puts("  'q' - Quit demo\n\n");
    
    int demo_active = 1;
    
    while(demo_active) {
        uart_puts("> ");
        
        // 读取命令
        char cmd = uart_getc();
        uart_putc(cmd);  // 回显
        uart_puts("\n");
        
        // 命令处理
        switch(cmd) {
            case 't': {
                unsigned long uptime = timer_uptime_ms();
                uart_puts("System uptime: ");
                // 打印uptime (简化版本)
                char uptime_str[20];
                unsigned long temp = uptime;
                int i = 0;
                
                do {
                    uptime_str[i++] = (temp % 10) + '0';
                    temp /= 10;
                } while (temp > 0);
                
                // 反转字符串
                for (int j = 0; j < i/2; j++) {
                    char t = uptime_str[j];
                    uptime_str[j] = uptime_str[i-j-1];
                    uptime_str[i-j-1] = t;
                }
                uptime_str[i] = '\0';
                
                uart_puts(uptime_str);
                uart_puts(" ms\n");
                break;
            }
            
            case 'i': {
                uart_puts("Timer information:\n");
                uart_puts("  Current mtime: ");
                uint64_t current = timer_read();
                uart_put_hex(current);
                uart_puts("\n");
                uart_puts("  Interrupt interval: 1 second (");
                uart_puts("10000000");  // CLOCK_FREQ
                uart_puts(" cycles)\n");
                break;
            }
            
            case 'm': {
                // 显示内存统计信息
                memory_stats();
                break;
            }
            
            case 'a': {
                // 运行内存测试
                memory_test();
                break;
            }
            
            case 'l': {
                // 显示所有任务状态
                task_info();
                break;
            }
            
            case 'c': {
                // 创建计数器任务
                uart_puts("Creating counter task...\n");
                int id = task_create("Counter", counter_task);
                if(id >= 0) {
                    uart_puts("Counter task created with ID: ");
                    char id_str[3] = {id + '0', '\n', '\0'};
                    uart_puts(id_str);
                }
                break;
            }
            
            case 'e': {
                // 创建内存测试任务
                uart_puts("Creating memory test task...\n");
                int id = task_create("MemTest", memory_test_task);
                if(id >= 0) {
                    uart_puts("Memory test task created with ID: ");
                    char id_str[3] = {id + '0', '\n', '\0'};
                    uart_puts(id_str);
                }
                break;
            }
            
            case 'y': {
                // 强制任务切换
                uart_puts("Forcing task switch...\n");
                task_yield();
                break;
            }
            
            case 'q':
                uart_puts("Exiting demo...\n");
                demo_active = 0;
                break;
                
            default:
                uart_puts("Unknown command. Available commands:\n");
                uart_puts("  't' - Show system uptime\n");
                uart_puts("  'i' - Show timer info\n");
                uart_puts("  'm' - Show memory stats\n");
                uart_puts("  'a' - Run memory test\n");
                uart_puts("  'l' - List all tasks\n");
                uart_puts("  'c' - Create counter task\n");
                uart_puts("  'e' - Create memory test task\n");
                uart_puts("  'y' - Force task switch (yield)\n");
                uart_puts("  'q' - Quit demo\n");
        }
    }
    
    // 退出演示后的主循环
    uart_puts("\n=== Demo Ended ===\n");
    uart_puts("System will now idle. Tasks will continue running.\n");
    
    // 显示最终状态
    uart_puts("\nFinal system status:\n");
    memory_stats();
    task_info();
    
    // 开始任务调度
    task_start();
    
    // 不会执行到这里
    while(1);
}
